// pages/chat/chat.js
const app = getApp();
const request = require('../../utils/request.js');
const util = require('../../utils/util.js');
const WsRootUrl = app.globalData.REQUSET_WS_IP_HEAD;
const ApiRootUrl = app.globalData.REQUEST_IP_HEAD;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    wsUrl: "",
    socketOpen: false,
    isHeartBeat: true,
    chatSocket: null,

    fromId: '', //自己的id
    toId: '', //对方的id
    meAvatar: '', //自己的头像
    youAvatar: '', //对方的头像

    inputValue: null,
    inputButtom: 0,
    chatList: [],
    words: "",
    scrollTop: 0,
    toView: "toView",
    flag: 0,
    sendFlag: 0
  },
  /**
   * 发送聊天
   */
  send() {
    //验证非空白信息
    if (this.data.words.replace(/\s+/g, '').length == 0) {
      wx.showToast({
        title: '不发送空白信息',
        icon: 'none'
      })
      return;
    }
    //发送聊天数据
    this.setData({
      sendFlag: 1
    })
    let msg = JSON.stringify({
      content: this.data.words,
    })
    this.sendSocketMessage(msg);
  },
  /**
   * 每当输入时刷新文本内容
   * @param {*} e 
   */
  getWords(e) {
    this.setData({
      words: e.detail.value
    })
  },
  /**
   * 收起键盘
   * @param {*} e 
   */
  InputBlur(e) {
    this.setData({
      inputBottom: 0
    })
  },
  /**
   * 拉起键盘
   * @param {*} e 
   */
  InputFocus(e) {
    this.setData({
      inputBottom: e.detail.height
    })
  },
  /**
   * 获取聊天内容
   */
  getChatList() {
    var that = this;
    request.get("/chat/getPage", {
      currentPage: 1,
      pageSize: 10,
      fromId: that.data.fromId,
      toId: that.data.toId,
      deleted: 0
    }).then((res) => {
      if (res.code == 200) {
        let chatList = res.data.records;
        for (let i = 0; i < chatList.length; i++) {
          chatList[i].displayTime = util.dealWithTime(chatList[i].time);
        }
        that.setData({
          chatList: chatList
        })
        //定位底部
        if (that.data.flag == 0) {
          that.setData({
            toView: "toView",
            flag: 1
          })
        }
        // 已读
        that.setRead();
      } else {
        util.showToast(res.msg, 'none');
      }
    }).catch((errMsg) => {
      util.showToast(errMsg, 'error');
    })
  },
  /**
   * 连接WebSocket服务器
   */
  connectWebSocket: function () {
    this.data.isHeartBeat = false;
    var that = this
    let chatSocket;
    chatSocket = wx.connectSocket({
      url: that.data.wsUrl,
      success: function (res) {
        console.log('WebSocket连接成功');
      },
      fail: function (res) {
        console.log('WebSocket连接失败:', res);
        util.showToast("网络异常，请检查网络", 'none');
      }
    })
    chatSocket.onOpen(function (res) {
      console.log('WebSocket连接已打开');
      // 打开心跳
      that.data.isHeartBeat=true;
    })
    chatSocket.onError(function (res) {
      console.log('WebSocket连接打开失败:', res);
      util.showToast("网络异常，请检查网络", 'none');
    })
    chatSocket.onClose(function (res) {
      console.log('WebSocket连接已关闭:', res)
    })
    chatSocket.onMessage(function (res) {
      console.log('接收到服务器发送的数据:', res.data)
      let result = JSON.parse(res.data);
      if (result.code == 200) {
        let chatList = that.data.chatList;
        for (let i = 0; i < chatList.length; i++) {
          chatList[i].displayTime = util.dealWithTime(chatList[i].time);
        }
        result.data.displayTime = util.dealWithTime(result.data.time);
        chatList.push(result.data);
        that.setData({
          chatList: chatList
        })
        //定位底部
        if (that.data.flag == 0) {
          that.setData({
            toView: "toView",
            flag: 1
          })
        }
        // 已读
        that.setRead();
      } else if (result.code == 666) {
        that.setData({
          socketOpen: true
        })
      } else {
        util.showToast(result.msg, 'none');
      }
    })
    this.setData({
      chatSocket: chatSocket
    })
  },
  /**
   * 发送WebSocket消息
   */
  sendSocketMessage: function (message) {
    let chatSocket =  this.data.chatSocket;
    const sendFlag = this.data.sendFlag;
    const that = this;
    chatSocket.send({
      data: message,
      success: function () {
        if(sendFlag == 1){
          that.setData({
            words: "",
            flag: 0,
            sendFlag: 0
          })
        }
      },
      fail: function (err) {
        console.error('消息发送失败', err);
        if(sendFlag == 1){
          that.setData({
            sendFlag: 0
          })
          util.showToast("发送失败", 'error');
        }
      }
    });
  },
  /**
   * 自制心跳包
   */
  heartBeat() {
    if (this.data.isHeartBeat) {
      this.data.socketOpen = false;
      this.sendSocketMessage("HeartBeatFromMultipleApp");
      const that = this;
      let chatSocket =  this.data.chatSocket;
      setTimeout(function () {
        if (!that.data.socketOpen) {
          if(chatSocket != null){
            chatSocket.close();
          }
          that.connectWebSocket();
        }
        that.heartBeat();
      }, 5000);
    }
  },

  /**
   * 设置已读
   */
  setRead() {
    var that = this;
    request.post('/chat/setRead', {
      fromId: that.data.fromId,
      toId: that.data.toId
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 页面标题
    wx.setNavigationBarTitle({
      title: options.youName + ' (' + options.youUnit + ')',
    })
    var fromId = wx.getStorageSync('userInfo').id;
    //赋值角色信息
    this.setData({
      toId: options.youId,
      fromId: fromId,
      wsUrl: WsRootUrl + "/wsChat/" + fromId + "/" + options.youId,
      // toId: "120a",
      // fromId: "202008764230",
      youAvatar: options.youAvatar,
      meAvatar: ApiRootUrl + wx.getStorageSync('userInfo').avatar,
    })
    // 初始化获取信息列表
    this.getChatList();
    // 连接WebSocket服务器, 开启获取信息
    this.connectWebSocket();
    // 开始心跳，需要等一会，连接上服务器才开始心跳
    const that = this;
    setTimeout(function () {
      that.heartBeat();
    }, 5000);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 关闭WebSocket连接
    if(this.data.chatSocket != null){
      this.data.chatSocket.close()
    }
    // 关闭心跳
    this.data.isHeartBeat = false;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 关闭WebSocket连接
    if(this.data.chatSocket != null){
      this.data.chatSocket.close()
    }
    // 关闭心跳
    this.data.isHeartBeat = false;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})